<!--
 * @Author: Bennty
 * @Date: 2024-07-18 14:29:34
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-09-14 16:08:13
 * @Description: 请填写简介
-->
<template>
    <div class="p-2">
        <transition
            :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave"
        >
            <div class="search">
                <el-form :model="queryParams" :inline="true" ref="queryFormRef" label-width="85px">
                    <el-form-item label="模糊搜索" prop="customerName">
                        <el-input  v-model="queryParams.customerName" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="所属人" prop="linkName">
                        <el-select v-model="queryParams.linkName" placeholder="请选择">
                            <el-option v-for="user in roleKeyUserList" :key="user.userId" :label="user.userName" :value="user.userName"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="上次跟进人" prop="lastContactPersonId">
                        <el-select v-model="queryParams.lastContactPersonId" placeholder="请选择">
                            <el-option v-for="user in roleKeyUserList" :key="user.userId" :label="user.userName" :value="user.userName"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="线索状态" prop="clueStatus">
                        <el-select v-model="queryParams.clueStatus">
                            <el-option label="开启" :value="1"></el-option>
                            <el-option label="关闭" :value="0"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="8" class="mb8">
                    <el-col class="header-button-container" :span="1.5">
                        <el-button type="success" plain icon="Plus" @click="handleAddClue">新增线索</el-button>
                    </el-col>
                </el-row>
            </template>
            <el-table  v-loading="loading" :data="clueList" highlight-current-row @current-change="handleCurrentChange">
                <el-table-column label="客户名称" prop="customerName" align="center"></el-table-column>
                <el-table-column label="联系人" prop="linkName" align="center"></el-table-column>
                <el-table-column label="线索来源" width="190" align="center">
                    <template #default="scope">
                        {{ customer_source.filter((item:any)=>item.value == scope.row.customerSource)[0].label }}
                    </template>
                </el-table-column>
                <el-table-column label="联系电话" prop="linkMobile" align="center" ></el-table-column>
                <el-table-column label="联系微信" prop="weChat" align="center" ></el-table-column>
                <el-table-column label="最近跟进信息" prop="remark" align="center">
                </el-table-column>
                <el-table-column label="上次跟进时间" width="190" prop="lastContactDate" align="center" ></el-table-column>
                <el-table-column label="下次跟进时间" prop="nextContactDate" align="center" ></el-table-column>
                <el-table-column label="上次跟进人" prop="lastContactPerson" align="center" ></el-table-column>
                <el-table-column label="上次跟进方式"  align="center" >
                    <template #default="scope">
                        {{ contract_type.filter((item:any)=>item.value == scope.row.lastFollowMethod)[0].label }}
                    </template>
                </el-table-column>
                <el-table-column label="线索状态" align="center">
                    <template #default="scope">
                        <span class="open" v-if="scope.row.clueStatus == '1'">开启</span>
                        <span class="close" v-else>关闭</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="190" align="center">
                    <template #default="scope">
                        <div class="operation">
                            <el-tooltip content="查询跟进记录" placement="top">
                                <el-button link type="primary" :style="{fontSize:'16px'}"  icon="Notebook" @click="handleClickClueFollow(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="新增跟进记录" placement="top">
                                <el-button link type="warning" :style="{fontSize:'16px'}"  icon="DocumentAdd" @click="handleClickAddClueFollow(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="更改状态" placement="top">
                                <el-button link :style="{fontSize:'16px', color:'#800080'}"  icon="Refresh" @click="handleChangeStatus(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <el-button link type="danger" :style="{fontSize:'16px'}"  icon="Delete" @click="handleDeleteClue(scope.row)"></el-button>
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="标记" align="center">
                    <template #default="scope">
                        <el-button v-if="scope.row.signFlag == '1'" :style="{color:'orange',fontSize:'30px'}" link @click="handleClickMark(scope.row)">
                            <el-icon color="#ffcc00"><StarFilled /></el-icon>
                        </el-button>
                        <el-button :style="{fontSize:'30px'}" v-else link @click="handleClickMark(scope.row)">
                            <el-icon><Star /></el-icon>
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="totalData > 0" :total="totalData" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                @pagination="getClues" />
        </el-card>
        <addClue :visible="addDialogVisible" :customerSource="customer_source" :contract="contract_type" @submit="handleSubmitAdd" @close="handleCancelAdd"/>
        <checkClueReport :visible="checkClueFollowVisible" :followList="followRecordList" @close="handleCancelClueFollow" />
        <addClueFollow :visible="addClueFollowVisible" :data="clueDetails" :contract="contract_type" @submit="handleSubmitAddClueFollow" @close="handleCancelAddClueFollow" />
    </div>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus';
import { getClueApi,updateClueApi,updateClueStatusApi,getClueInfoByIdApi,deleteClueByIdApi } from '@/api/sj/clue-crm/index';
import { getFollowRecordByIdApi } from '@/api/sj/followRecord-crm/index';
import { getCustomerApi } from '@/api/sj/customer-crm/index';
import useCRMStore from '@/store/modules/crm';
import { clueVO } from '@/api/sj/clue-crm/types';
import { CustomerVO } from '@/api/sj/customer-crm/types';
import addClue from './components/addClue.vue';
import checkClueReport from './components/checkClueReport.vue';
import addClueFollow from './components/addClueFollow.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { customer_source,contract_type } = toRefs<any>(proxy?.useDict('customer_source','contract_type'));
const queryFormRef = ref<FormInstance>();
const { getUserListByRoleKey } = useCRMStore();
const { roleKeyUserList } = toRefs(useCRMStore());
const data = reactive({
    queryParams:{
        pageNum: 1,
        pageSize: 30,
        customerName: undefined,
        linkName: undefined,
        lastContactPersonId: undefined,
        clueStatus: undefined
    }
});
const { queryParams } = toRefs(data);
const clueList = ref<clueVO[]>([]);
const loading = ref(false);
const totalData = ref(0);
const currentRow = ref();
const customerList = ref<CustomerVO[]>([]);
const clueDetails = ref<any>();
const followRecordList = ref<any[]>([]);
const addDialogVisible = ref(false);
const checkClueFollowVisible = ref(false);
const addClueFollowVisible = ref(false);

const getCustomers = async ()=>{
    const customerParams = {
        pageNum: 1,
        pageSize: 999,
    }
    const { rows } = await getCustomerApi(customerParams);
    customerList.value = rows;
};

const getClues = async ()=>{
    loading.value = true;
    const {rows,total} = await getClueApi(queryParams.value);
    clueList.value = rows;
    totalData.value = total; 
    loading.value = false;
};

/** 根据id获取线索详情 */
const getClueInfoById = async (id: any) => {
    const result = await getClueInfoByIdApi(id);
    clueDetails.value = result.data;
    return result;
};

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
};

const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};

const handleCurrentChange = (val: any) => {
    currentRow.value = val;
};

/**点击标识按钮 */
const handleClickMark = async (row: clueVO)=>{
    const submitData = {
        ...row,
        signFlag: row.signFlag == '1'?0:1
    }
    await updateClueApi(submitData).then((result)=>{
        if(result.code == 200){
            getClues();
        }
    });
};

/** 点击新增线索 */
const handleAddClue = ()=>{
    addDialogVisible.value = true;
};

const handleSubmitAdd = (result: boolean)=>{
    if(result){
        handleCancelAdd();
    };
};

const handleCancelAdd = ()=>{
    addDialogVisible.value = false;
};

/** 点击查看线索跟进记录 */
const handleClickClueFollow = async (row:clueVO)=>{
    await getFollowRecordByIdApi(row.id).then((result)=>{
        if(result.code == 200){
            followRecordList.value = {...result.data};
            checkClueFollowVisible.value = true;
        }
    });
};

const handleCancelClueFollow = ()=>{
    checkClueFollowVisible.value = false;
};

/** 点击新增线索跟进 */
const handleClickAddClueFollow = (row: clueVO)=>{
    getClueInfoById(row.id).then(result=>{
        if(result.code == 200){
            addClueFollowVisible.value = true;
        }
    });
};

const handleSubmitAddClueFollow = (result: boolean) => {
    if(result){
        getClues();
        handleCancelAddClueFollow();
    };
};

const handleCancelAddClueFollow = ()=>{
    addClueFollowVisible.value = false;
};

/** 点击更新线索状态 */
const handleChangeStatus = async (row: clueVO)=>{
    const tips = row.clueStatus == '1'?'当前线索状态为开启，是否要关闭此线索？':'当前线索状态为关闭，是否要开启此线索？';
    const submitData = {
        id: row.id,
        clueStatus: row.clueStatus == '1'? 0:1
    }
    await proxy?.$modal.confirm(tips);
    await updateClueStatusApi(submitData).then((result)=>{
        if(result.code == 200){
            proxy?.$modal.msgSuccess("更改状态成功");
            getClues();
        }
    });
    
};

const handleDeleteClue = async (row: clueVO)=>{
    await proxy?.$modal.confirm('确定要删除该线索?');
    await deleteClueByIdApi(row.id).then(result=>{
        if(result.code == 200){
            proxy?.$modal.msgSuccess("删除线索成功");
            getClues();
        }
    });
};

onMounted(()=>{
    getCustomers();
    getClues();
    getUserListByRoleKey('business_role');
    
});
</script>

<style lang="scss" scoped>
.open{
    color: yellowgreen;
}
.close{
    color: red;
}
</style>